package com.ruoyi.auth.controller;

import com.ruoyi.auth.service.MSMService;
import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.auth.util.MobileUtil;
import com.ruoyi.common.core.utils.RandomUtil;
import com.ruoyi.common.redis.service.RedisService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/msm")
public class MSMController {
    @Autowired
    private MSMService msmService;

    @Autowired
    private RedisService redisService;

    //发送手机验证码,redis设置过期时间
    @GetMapping("/sendmessage")
    public AjaxResult sendCode(@Param("phone") String phone) {
        boolean sendphone = sendphone(phone, CacheConstants.MSG_REGISTER_KEY);
        return AjaxResult.success();
    }

    @GetMapping("/findpwmessage")
    public AjaxResult sendCode_findpwmessage(@Param("phone") String phone) {
        //先从redis取到验证码,获取到就返回ok
        boolean sendphone = sendphone(phone, CacheConstants.MSG_FINDPW_KEY);
        return AjaxResult.success();
    }

    private boolean sendphone(String phone, String key) {
        if(!MobileUtil.checkPhone(phone)){
            throw new ServiceException("手机号格式错误");
        }
        //key:手机号 value:验证码
        String code = redisService.getCacheObject( key+ phone);
        if (!StringUtils.isEmpty(code)) {
            return true;
        }
        //如果从redis获取不到，生成验证码，整合短信服务发送
        //6位验证码
        code = RandomUtil.code();
        //整合阿里云信服务发送
        boolean isSend = msmService.send(phone, code);
        if (isSend) {
            //成功,放到redis,2分钟有效
            redisService.setCacheObject(key+ phone, code, 2l, TimeUnit.MINUTES);//key value 有效时间 时间单位
            return true;
        } else {
            throw new ServiceException("发送短信失败");
        }
    }
}

